"""
参考示例: https://juejin.cn/post/7482671750209748992
"""

import asyncio
import json
import psycopg2  # 同步数据库驱动
import requests


### -------------------------------
# 示例1: 文件io异步读取
### -------------------------------
def read_large_file(filepath):
    # 同步阻塞操作
    with open(filepath, "r", encoding="utf-8") as f:
        data = json.load(f)
    return data


async def process_file():
    """示例1:
    文件io操作:异步读取文件
    """
    data = await asyncio.to_thread(read_large_file, "large_dataset.json")
    print(f"读取了{len(data)}条数据")
    return data


### -------------------------------
# 示例2: 数据库查询
### -------------------------------
def db_query(sql):
    conn = psycopg2.connect("dbname=test user=postgres")
    cur = conn.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    conn.close()
    return result


async def get_user_data(user_id):
    # 将同步数据库查询放入线程中执行
    sql = f"SELECT * FROM users WHERE id = {user_id}"
    result = await asyncio.to_thread(db_query, sql)
    return result


### -------------------------------
# 示例3: 网络请求
### -------------------------------
def fetch_api_data(url):
    response = requests.get(url, timeout=10)
    return response.json()


async def get_weather(city):
    api_url = f"https://api.weather.com/forecast?city={city}"
    # 将同步HTTP请求放入线程中执行
    data = await asyncio.to_thread(fetch_api_data, api_url)
    return data


### -------------------------------
# 示例4: cpu密集型任务
### -------------------------------
def calculate_prime_factors(num):
    """计算质因数分解(CPU密集型任务)"""
    factors = []
    d = 2
    while num > 1:
        while num % d == 0:
            factors.append(d)
            num //= d
        d += 1
        if d * d > num and num > 1:
            factors.append(num)
            break
    return factors


async def process_numbers():
    results = []
    for i in range(100000, 100010):
        # 将CPU密集型任务放入线程中执行
        factors = await asyncio.to_thread(calculate_prime_factors, i)
        results.append((i, factors))
    return results
